package com.ds.infra.rpc.core.transport.client.handler;

import com.ds.infra.rpc.core.cache.RpcResponseCache;
import com.ds.infra.rpc.core.protocol.RpcProtocol;
import com.ds.infra.rpc.core.protocol.RpcResponse;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;

/**
 * 处理服务端响应（线程安全）
 *
 * @author WeiShaoying
 */
@Slf4j
@ChannelHandler.Sharable
public class RpcResponseHandler extends SimpleChannelInboundHandler<RpcProtocol<RpcResponse>> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcProtocol<RpcResponse> protocol) {
        RpcResponse response = protocol.getBody();
        if (response == null) {
            log.error("Received null response");
            return;
        }

        CompletableFuture<RpcResponse> future = RpcResponseCache.get(response.getRequestId());
        if (future != null) {
            future.complete(response);
            log.debug("Processed response for request: {}", response.getRequestId());
        } else {
            log.warn("No matching request found for response ID: {}", response.getRequestId());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("Response handling error", cause);
        ctx.close();
    }
}
